/*
* utils 工具模块
* window.utilsLoad
* */
;(function (utilsLoad, $, window, document) {

    /*
    * 封装jquery ajax
    * @params: {
    *   type： 默认get
    *   url： 接口地址
    *   contentType： 默认'application/json'
    *   headers: 请求头
    *   data： 请求数据, Object/String
    * }
    * */

    window.$reAjax = function (config, completeFn, beforeFn) {
        config = config || {};
        config.method = config.method || 'get';
        config.url = config.url || '';
        config.contentType = config.contentType || 'application/json';
        config.dataType = config.dataType || 'json';
        config.processData = config.processData || true;
        config.headers = config.headers || {};
        config.data = config.data || {};

        if(config.contentType === 'form'){
            config.contentType = 'application/x-www-form-urlencoded';
        }

        if(!config.url){
            console.error('缺少url地址');
            return false;
        }
        $.ajax({
            method: config.method,
            url: config.url,
            xhrFields: {
                withCredentials: config.withCredentials || false
            },
            processData: config.processData,
            dataType: config.dataType,
            contentType: config.contentType,
            headers: config.headers,
            data: config.data,
            beforeSend: beforeFn || function () {},
            complete: completeFn || function () {}
        })
    };

    /*
    * utils 工具模块
    * Object：{
    *    '返回值': utilsLoad (Object)
    * }
    * */

    var utils = (function () {

        //获取url参数
        var getQueryString = function(name) {
            var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
            var r = window.location.search.substr(1).match(reg);
            if (r != null) return decodeURI(r[2]);
            return null;
        };

        //删除url中指定参数
        var delQueryUrl = function(url, ref) {
            var str = "";
            if (url.indexOf('?') != -1){
                str = url.substr(url.indexOf('?') + 1)
            }else{
                return url
            }
            var arr = "",
                returnurl = "";
            if (str.indexOf('&') != -1) {
                arr = str.split('&');
                for (var i in arr) {
                    if (arr[i].split('=')[0] != ref) {
                        returnurl = returnurl + arr[i].split('=')[0] + "=" + arr[i].split('=')[1] + "&";
                    }
                }
                return url.substr(0, url.indexOf('?')) + "?" + returnurl.substr(0, returnurl.length - 1);
            }
            else {
                arr = str.split('=');
                if (arr[0] == ref){
                    return url.substr(0, url.indexOf('?'))
                }else{
                    return url
                }
            }
        };

        //验证手机号
        var validatePhone = function (str) {
            if(/^1[1-9][0-9]{9}$/.test(str)){
                return true
            }
            return false
        };

        //验证邮箱
        var validateEmail = function (str){
            if(/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/.test(str)){
                return true
            }
            return false
        };

        //防抖
        var debounce = function (fn, delay){
            var timer = null;
            return function () {
                var _this = this,
                    args = arguments;
                timer && clearTimeout(timer);
                timer = setTimeout(function () {
                    fn.apply(_this, args);
                    timer = null
                }, delay)
            }
        };

        //节流
        var throttle = function (fn, delay){
            var timer = null;
            return function (){
                if(timer) {
                    return false
                }
                var _this = this,
                    args = arguments;
                timer = setTimeout(function (){
                    fn.apply(_this, args);
                    timer = null
                }, delay)
            }
        };

        //显示/隐藏输入的密码
        function togglePassword (_this){
            var $parent = $(_this).parent(),
                $input = $parent.find('input');
            $(_this).toggleClass('open');
            $input.attr('type', $(_this).hasClass('open') ? 'text' : 'password');
        }

        //验证码倒计时
        function countDown(el) {
            $(el).attr('disabled',true);
            var time = 120,
                down = setInterval(function(){
                    time --;
                    $(el).html(time + 's');
                    if(time === 0){
                        clearInterval(down);
                        $(el).removeAttr('disabled').html('获取');
                        return false;
                    }
            }, 1000)
        }

        // 设置cookie
        function setCookie(name, value, day) {
            var exp = new Date();
            exp.setTime(exp.getTime() + (day || 1)*24*60*60*1000);
            document.cookie = name + "="+ encodeURIComponent(value)
                            + ";expires=" + exp.toGMTString()
                            + ";path=/"
                            + (getCookie("CURRENT_ENV") === "production" ? ";domain="+ONLINE_DOMAIN : ";")
        }

        // 获取cookie
        function getCookie(name) {
            var arr,
                reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
            if (arr = document.cookie.match(reg)) {
                return decodeURIComponent(arr[2]);
            } else {
                return null;
            }
        }

        // 限制最大输入字符数
        function maxInput(inputEl, targetEl, length, callback) {
            var maxLength = length || 500,
                valLength = $(inputEl).val().length;
            if(valLength > maxLength){
                callback ? callback() : alert('输入内容长度超过限制');
                $(inputEl).val($(inputEl).val().slice(0, maxLength))
            }
            $(targetEl).html($(inputEl).val().length + '/' + maxLength)
        }

        // create script
        function createScript (config, onload){
            var script = document.createElement('script');
            script.type = 'text/javascript';
            script.src = config.src;
            config.defer && (script.defer = true);
            config.async && (script.async = true);
            document.head.appendChild(script);
            script.onload = function (){
                onload && onload()
            }
        }

        // loading
        function myLoading (config){
            config = config || {};
            $('body').append(`
                              <div class="layui-layer layui-layer-loading my-loading" style="top: ${config.top || '45%'}">
                                 <div class="layui-layer-content layui-layer-loading2"></div>
                                 <span class="layui-layer-setwin"></span>
                              </div>
                            `)
        }
        // unloading
        function unMyLoading (){
            $('.my-loading').remove()
        }

        return {
            getQueryString,
            delQueryUrl,
            validatePhone,
            validateEmail,
            togglePassword,
            countDown,
            debounce,
            throttle,
            getCookie,
            setCookie,
            maxInput,
            myLoading,
            unMyLoading,
            createScript
        }
    }());

    window.utilsLoad = Object.assign(utilsLoad, utils)

}(window.utilsLoad || {}, jQuery, window, document));

